import * as WXAPI from '@/api/wx/login.js'
const User = {
  state: {
    memberId: null,
    openid: null,
    username: '未登录',
    nickname: '',
    userinfo: null,
    code: null,
    token: null
  },
  getters: {
    isLogin: state => {
      return !(state.openid === null)
    },
    name: state => {
      return state.nickname
    },
    avatar: state => {
      return state.userinfo.headimgurl || '/static/img/person.png'
    },
    token: state => {
      return state.token
    }
  },
  mutations: {
    login (state, code) {
      state.code = code
    },
    SET_USERINFO (state, userinfo) {
      state.openid = userinfo.openid
      state.memberId = userinfo.id
      state.username = userinfo.username
      state.userinfo = userinfo
    },
    logout (state) {
      state.code = null
      state.memberId = null
      state.openid = null
      state.username = null
      state.userinfo = null
    }
  },
  actions: {
    doRedirectHandle({ commit }, routeName) {
      // 缓存页面
      sessionStorage.setItem('beforeRouterName', routeName)
      // 跳转授权页面
      window.location.href = WXAPI.getRedirectUrl()
    },
    doLogin({ commit }, code, state) {
      return new Promise((resolve, reject) => {
        WXAPI.login(code, state).then(res => {
          commit('SET_USERINFO', res.data)
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    doLogout({ commit }) {
      return new Promise((resolve) => {
        commit('logout')
        resolve()
      })
    }
  }
}
export default User
